﻿using System;
using System.Net;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Documents;
using System.Windows.Ink;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Animation;
using System.Windows.Shapes;
using System.Windows.Browser;
using System.Runtime.Serialization.Json;
using System.IO;
using System.Text;

namespace UI.Web.SL.Demo.SysAdmin.Common
{
    public class Utility
    {
        //获取Cookie中的值
        public string GetCookie(string key)
        {
            string[] cookies = HtmlPage.Document.Cookies.Split(';');//cookie里含多对值,将值按;分割  
            foreach (string cookie in cookies)
            {
                string[] value = cookie.Split('=');//获取=两边的值  
                if (value.Length == 2)
                {
                    if (value[0].Trim() == key)//判断键名
                    {
                        return value[1];//返回键值  
                    }
                }
            }
            return "";
        }

        //清空Cookie
        public static void DeleteCookie(string key)
        {
            string oldCookie = HtmlPage.Document.GetProperty("cookie") as String;
            DateTime expiration = DateTime.UtcNow - TimeSpan.FromDays(1);
            string cookie = String.Format("{0}=;expires={1}", key, expiration.ToString("R"));
            HtmlPage.Document.SetProperty("cookie", cookie);
        }

        /// <summary>
        /// 添加Cookie
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        public static void SetCookie(string key, string value)
        {
            DateTime expires = DateTime.Now + TimeSpan.FromDays(7); //cookie的有效时间  
            string cookie = String.Format("{0}={1};expires={2}", key, value, expires.ToString("R"));
            HtmlPage.Document.SetProperty("cookie", cookie);
        }
        /// <summary>
        /// 
        /// </summary>
        /// <param name="tar"></param>
        /// <returns></returns>
        public static object DeepCopy(object tar)
        {
            MemoryStream ms = new MemoryStream();
            var jsonSerializer = new DataContractJsonSerializer(tar.GetType());
            jsonSerializer.WriteObject(ms, tar);
            var result = jsonSerializer.ReadObject(ms);
            return result;
        }
    }
}
